package 多线程.线程池;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description
 *
 * @Author: Heiffeng
 * @Date: 2021/12/18 14:13
 */
public class ThreadPoolExecutor构造参数探究 {

    int corePoolSize = 1;
    int maximumPoolSize = 2;
    int keepAliveTime = 2;

    int threadNum = 7;

    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(5));

    @Test
    public void test1() throws InterruptedException {
        for (int i = 0; i < threadNum; i++) {
            threadPool.execute(()->{
                try {Thread.sleep(1000);
                } catch (InterruptedException e) {e.printStackTrace();}
                System.out.println(Thread.currentThread().getName()+" Exec... ");
            });
            System.out.printf("corePoolSize:%d,poolSize:%d,queueSize:%d \n",
                    threadPool.getCorePoolSize(),
                    threadPool.getPoolSize(),
                    threadPool.getQueue().size());
        }
        Thread.sleep(5100);
        System.out.printf("corePoolSize:%d,poolSize:%d,queueSize:%d \n",
                threadPool.getCorePoolSize(),
                threadPool.getPoolSize(),
                threadPool.getQueue().size());
        new CountDownLatch(1).await();
    }

    /**
     * 案例分析
     * 当threadNum小于7时，queueSize + corePoolSize 就能包容这些线程。所以不会使用maximumPoolSize
     * 当threadNum等于7时，queueSize + maximumPoolSize 刚好能包容7个线程，因为线程数超过queueSize+corePoolSize，所以启用maximumPoolSize
     * 当threadNum大于7时，queueSize + maximumPoolSize 不能包容这些线程，因此启用了默认的拒绝策略。直接抛出了异常。
     *
     * 因为最大只有两个线程在执行，每个任务耗时1秒。当线程数为7时，
     * 由maximumPoolSize-corePoolSize临时扩充出来的线程，最快会在3秒后空闲。因此，会在 3+keepAliveTime秒后被超时销毁
     */
}
